package com.minelx.statementsplus.cha.webauto;

import com.minelx.landisk.filesystem.core.File;
import com.minelx.util.IOUtil;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.StandardOpenOption;

public class DownloadRequest {

	private final String secretKey;

	private final String sessionId;

	public DownloadRequest(String secretKey, String sessionId) {
		this.secretKey = secretKey;
		this.sessionId = sessionId;
	}

	public void doDownload(File file) {
		try {
			IOUtil.exchange(getInputStream(), getOutputStream(file));
		} catch (IOException e) {
			throw new RuntimeException("something is wrong here", e);
		}
	}

	private InputStream getInputStream() {
		while (true) {
			try {
				CloseableHttpClient httpClient = HttpClientBuilder.create().build();
				CloseableHttpResponse response = httpClient.execute(buildGetRequest());
				return response.getEntity().getContent();
			} catch (IOException ignored) {
			}
		}
	}

	private OutputStream getOutputStream(File file) {
		try {
			return file.outputStream(StandardOpenOption.CREATE);
		} catch (IOException e) {
			throw new RuntimeException("something is wrong here", e);
		}
	}

	public HttpGet buildGetRequest() {
		HttpGet result = new HttpGet(ChaPage.URL_HEAD + "/api.php?a=getfile&s=" + secretKey + "&t=" + Math.random());
		result.addHeader("Cookie", sessionId);
		return result;
	}
}
